package com.example.demo.excel.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.example.demo.entity.base.ResponseEntity;
import com.example.demo.entity.excel.UserExcelModel;
import com.example.demo.excel.listener.UserImportListener;
import com.example.demo.util.EmptyUtil;
import com.example.demo.util.ResponseFactory;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ExcelModelService {
	public ResponseEntity<Map<String, String>> importUsers(MultipartFile excelFile){
		
		List<Map<String, String>> errorContext = new ArrayList<>();
		
		try {
			EasyExcel.read(excelFile.getInputStream(), UserExcelModel.class, new UserImportListener(errorContext)).sheet().doRead();
		} catch (IOException e) {
			log.error("上传的excel文件无法读取",e);
			return ResponseFactory.setFail("上传的excel文件无法读取");
		}
		
		if(EmptyUtil.isNotEmpty(errorContext)) {
			return ResponseFactory.setFail(501, "部分用户导入失败", errorContext);
		}
		
		return ResponseFactory.setSuccess("excel中填写的用户全部导入成功!");
	}
}
